package com.java.test;

import okhttp3.*;
import okhttp3.logging.HttpLoggingInterceptor;
import okio.Buffer;
import okio.BufferedSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.web3j.protocol.exceptions.ClientConnectionException;
import org.web3j.protocol.http.HttpService;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class HttpServiceEx extends HttpService {
    private static final Logger log = LoggerFactory.getLogger(HttpServiceEx.class);
    private static OkHttpClient createOkHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
//        configureLogging(builder);
        log.info("---------设置超时时间--------{}秒",120);
        builder.connectionPool(new ConnectionPool())
                .connectTimeout(120, TimeUnit.SECONDS)
                .readTimeout(120, TimeUnit.SECONDS).build();
        return builder.build();
    }
    public static final MediaType JSON_MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8");
    private OkHttpClient httpClient;
    private final String url;
    private final boolean includeRawResponse;
    private HashMap<String, String> headers;

    public HttpServiceEx(String url, OkHttpClient httpClient, boolean includeRawResponses) {
        super(includeRawResponses);
        this.headers = new HashMap();
        this.url = url;
        this.httpClient = httpClient;
        this.includeRawResponse = includeRawResponses;
    }

    private HttpServiceEx(String url, OkHttpClient httpClient) {
        this(url, httpClient, false);
    }

    public HttpServiceEx(String url) {
        this(url, createOkHttpClient());
    }

    public HttpServiceEx(String url, boolean includeRawResponse) {
        this(url, createOkHttpClient(), includeRawResponse);
    }

    private static void configureLogging(OkHttpClient.Builder builder) {
        if (log.isDebugEnabled()) {
            Logger var10002 = log;
            var10002.getClass();
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor(var10002::debug);
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(logging);
        }

    }

    protected InputStream performIO(String request) throws IOException {
        RequestBody requestBody = RequestBody.create(JSON_MEDIA_TYPE, request);
        Headers headers = this.buildHeaders();
        Request httpRequest = (new Request.Builder()).url(this.url).headers(headers).post(requestBody).build();
        Response response = this.httpClient.newCall(httpRequest).execute();
        if (response.isSuccessful()) {
            ResponseBody responseBody = response.body();
            return responseBody != null ? this.buildInputStream(responseBody) : null;
        } else {
            throw new ClientConnectionException("Invalid response received: " + response.body());
        }
    }

    private InputStream buildInputStream(ResponseBody responseBody) throws IOException {
        InputStream inputStream = responseBody.byteStream();
        if (this.includeRawResponse) {
            BufferedSource source = responseBody.source();
            source.request(9223372036854775807L);
            Buffer buffer = source.buffer();
            long size = buffer.size();
            if (size > 2147483647L) {
                throw new UnsupportedOperationException("Non-integer input buffer size specified: " + size);
            } else {
                int bufferSize = (int)size;
                BufferedInputStream bufferedinputStream = new BufferedInputStream(inputStream, bufferSize);
                bufferedinputStream.mark(inputStream.available());
                return bufferedinputStream;
            }
        } else {
            return inputStream;
        }
    }

    private Headers buildHeaders() {
        return Headers.of(this.headers);
    }

    public void addHeader(String key, String value) {
        this.headers.put(key, value);
    }

    public void addHeaders(Map<String, String> headersToAdd) {
        this.headers.putAll(headersToAdd);
    }

    public HashMap<String, String> getHeaders() {
        return this.headers;
    }
}
